package com.xinqi.modules.sys.stats.controller.admin;

import com.xinqi.common.base.response.R;
import com.xinqi.modules.sys.stats.dto.req.HomePageDayStQueryDTO;
import com.xinqi.modules.sys.stats.dto.rsp.HomePageDayStResultDTO;
import com.xinqi.modules.sys.stats.service.HomePageDayStService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * ADMIN -- 首页数据统计
 *
 * @author: linkai
 * @date: 2023/04/25
 */
@Slf4j
@Tag(name = "Admin-首页数据统计", description = "首页数据统计Admin接口")
@RestController
@RequestMapping("/admin/stats/home-page")
@RequiredArgsConstructor
public class HomePageDayStAdminController {
    private final HomePageDayStService homePageDayStService;
    private LocalDateTime nextUpdateDateTime;
    private static final int UPDATE_INTERVAL = 20;
    private final Object lock = new Object();

    @Operation(summary = "首页数据统计-当天")
    @GetMapping("/today")
    public R<HomePageDayStResultDTO> today(@Parameter(description = "开始日期", example = "2023-01-01") @RequestParam LocalDate statDate,
                                           @Parameter(description = "结束日期", example = "2023-01-01") @RequestParam LocalDate endDate) {
        HomePageDayStResultDTO dto = homePageDayStService.today(statDate, endDate);
        return R.data(dto);
    }

    @Operation(summary = "首页数据统计")
    @GetMapping("/list")
    public R<List<HomePageDayStResultDTO>> list(@ParameterObject HomePageDayStQueryDTO dto) {
        return R.data(homePageDayStService.list(dto));
    }

    @Operation(summary = "首页数据统计-更新")
    @GetMapping("/update-today")
    public R<Boolean> updateToday() {
        if (nextUpdateDateTime == null || LocalDateTime.now().isAfter(nextUpdateDateTime)) {
            synchronized (lock) {
                if (nextUpdateDateTime == null || LocalDateTime.now().isAfter(nextUpdateDateTime)) {
                    // 设置更新间隔
                    nextUpdateDateTime = LocalDateTime.now().minusMinutes(UPDATE_INTERVAL);
                    // 更新首页统计数据
                    homePageDayStService.updateToday();
                    log.error("更新首页统计数据成功");
                }
            }
        }
        return R.data(true);
    }

}
